import matplotlib.pyplot as plt
import numpy as np
from skimage import io, feature, exposure,transform
from skimage.color import rgb2gray
from matplotlib.patches import Rectangle
import argparse

# # 创建命令行参数解析器
# parser = argparse.ArgumentParser(description='计算并可视化图像的HOG特征')
# parser.add_argument('image_path', type=str, help='要处理的图像文件的路径')
# args = parser.parse_args()
#
# # 从指定路径加载图像
# try:
#     image = io.imread(args.image_path)
# except FileNotFoundError:
#     print(f"错误：未找到图像文件 {args.image_path}，请检查路径是否正确。")
#     exit(1)
image = io.imread(r'F:\人工智能教材编写\traffic_sign\train\17\017_1_0013.png')
# 将图像转换为灰度图并调整大小为 64x64
gray_image = rgb2gray(image)
resized_gray_image = transform.resize(gray_image, (64, 64))

# HOG 参数设置
orientations = 8
pixels_per_cell = (8, 8)
cells_per_block = (2, 2)

# 计算 HOG 特征并可视化
fd, hog_image = feature.hog(resized_gray_image, orientations=orientations,
                            pixels_per_cell=pixels_per_cell,
                            cells_per_block=cells_per_block,
                            visualize=True)

# 获取图像尺寸和 cell 数量
rows, cols = resized_gray_image.shape
cells_y, cells_x = (rows // pixels_per_cell[0], cols // pixels_per_cell[1])

# 创建一个 3 列的图像显示
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(18, 6))

# 显示原始图像
ax1.imshow(image)
ax1.set_title('原始图像')
ax1.axis('off')

# 显示调整后的灰度图像，添加 cell 网格
ax2.imshow(resized_gray_image, cmap=plt.cm.gray)
ax2.set_title('标记了 Cell 的灰度图像')

# 绘制 cell 网格
for i in range(cells_y):
    for j in range(cells_x):
        rect = Rectangle((j * pixels_per_cell[1], i * pixels_per_cell[0]),
                         pixels_per_cell[1], pixels_per_cell[0],
                         linewidth=1, edgecolor='r', facecolor='none')
        ax2.add_patch(rect)

ax2.axis('off')

# 显示 HOG 图像
ax3.imshow(hog_image, cmap=plt.cm.gray)
ax3.set_title('HOG 图像')
ax3.axis('off')

plt.tight_layout()
plt.show()